package com.sdygmedia.action.kindeditor.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.json.simple.JSONObject;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadImageAction2 extends ActionSupport {

	private final static String UPLOAD = "/attached";

	private File imgFile;

	private String imgFileFileName;

	private String imgFileContentType;

	public String getImgFileFileName() {
		return imgFileFileName;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	public String getImgFileContentType() {
		return imgFileContentType;
	}

	public void setImgFileContentType(String imgFileContentType) {
		this.imgFileContentType = imgFileContentType;
	}

	public File getImgFile() {
		return imgFile;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	@Override
	public String execute() throws Exception {

		InputStream in = new FileInputStream(imgFile);
		String dir = ServletActionContext.getRequest().getRealPath(UPLOAD);
		System.out.println(dir);

		OutputStream fos = new FileOutputStream(dir + "\\"
				+ this.getImgFileFileName());

		byte[] buffer = new byte[1024 * 1024];

		int length = 0;

		while (-1 != (length = in.read(buffer))) {
			fos.write(buffer, 0, length);

		}
		fos.close();
		in.close();

		JSONObject obj = new JSONObject();
		obj.put("error", 0);
		obj.put("url", dir + "\\" + this.getImgFileFileName());

		/*ActionContext ctx = ServletActionContext.getContext();
		
		HttpServletRequest req = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
		
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);
		
		Map session = ctx.getSession();  */
		
		ServletActionContext.getRequest().setAttribute("msg",
				obj.toJSONString());

		return "success";
	}
	
	

}
